# 做为终端测试urls用的
from django.core.management.base import BaseCommand
from django.urls import get_resolver, URLResolver, URLPattern


class Command(BaseCommand):
    help = 'List all registered URLs with view and reverse name'

    def handle(self, *args, **options):
        resolver = get_resolver()
        for pattern in resolver.url_patterns:
            self._print_patterns(pattern)

    def _print_patterns(self, pattern, parent_path='', namespace=''):
        """递归打印路由信息"""
        current_path = parent_path + str(pattern.pattern)

        # 处理 URLResolver (路由容器)
        if isinstance(pattern, URLResolver):
            # 合并命名空间
            new_namespace = pattern.namespace or namespace
            # 递归处理子路由
            for p in pattern.url_patterns:
                self._print_patterns(p, current_path, new_namespace)
            return

        # 处理 URLPattern (具体路由)
        if isinstance(pattern, URLPattern):
            # 获取视图标识
            view_info = getattr(pattern, 'lookup_str', 'Unknown View')

            # 构建完整反向名称
            reverse_name = pattern.name
            if namespace and reverse_name:
                reverse_name = f"{namespace}:{reverse_name}"

            # 输出三部分信息
            output = (
                f"{current_path.ljust(60)} "  # 路径
                f"-> {view_info.ljust(40)} "  # 视图函数
                f"(name: {reverse_name or 'None'})"  # 反向名称
            )
            self.stdout.write(output)

